import tkinter as tk
from tkinter import filedialog, messagebox
import os
import sys
import subprocess


class App:
    def __init__(self, root):
        self.root = root
        self.root.title("网页打包工具")
        self.root.geometry("600x500")

        # 输入字段
        self.url_var = tk.StringVar()
        self.name_var = tk.StringVar(value="MyWebApp")
        self.icon_var = tk.StringVar()
        self.width_var = tk.StringVar(value="800")
        self.height_var = tk.StringVar(value="600")

        # 界面布局（使用网格布局）
        tk.Label(root, text="网页地址或文件路径:").grid(row=0, column=0, sticky="w", pady=5)
        self.url_entry = tk.Entry(root, textvariable=self.url_var, width=50)
        self.url_entry.grid(row=0, column=1, columnspan=2, padx=5, pady=5)

        tk.Button(root, text="选择HTML文件", command=self.select_file).grid(row=0, column=3, padx=5)

        tk.Label(root, text="应用名称:").grid(row=1, column=0, sticky="w", pady=5)
        self.name_entry = tk.Entry(root, textvariable=self.name_var)
        self.name_entry.grid(row=1, column=1, columnspan=3, padx=5, pady=5)

        tk.Label(root, text="图标路径(ico/png):").grid(row=2, column=0, sticky="w", pady=5)
        self.icon_entry = tk.Entry(root, textvariable=self.icon_var)
        self.icon_entry.grid(row=2, column=1, columnspan=2, padx=5, pady=5)
        tk.Button(root, text="选择图标", command=self.select_icon).grid(row=2, column=3, padx=5)

        tk.Label(root, text="窗口尺寸:").grid(row=3, column=0, sticky="w", pady=5)
        tk.Label(root, text="宽度:").grid(row=3, column=1, sticky="e")
        self.width_entry = tk.Entry(root, textvariable=self.width_var, width=5)
        self.width_entry.grid(row=3, column=2, sticky="w")
        tk.Label(root, text="高度:").grid(row=4, column=1, sticky="e")
        self.height_entry = tk.Entry(root, textvariable=self.height_var, width=5)
        self.height_entry.grid(row=4, column=2, sticky="w")

        tk.Button(root, text="打包为应用", command=self.pack_app, bg="#4CAF50", fg="white").grid(
            row=5, column=0, columnspan=4, pady=15, sticky="ew"
        )

    def select_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("HTML文件", "*.html *.htm")])
        if file_path:
            self.url_var.set(file_path)

    def select_icon(self):
        icon_path = filedialog.askopenfilename(filetypes=[("图标文件", "*.ico *.png")])
        if icon_path:
            self.icon_var.set(icon_path)

    def pack_app(self):
        url = self.url_var.get()
        name = self.name_var.get()
        icon = self.icon_var.get()
        width = self.width_var.get()
        height = self.height_var.get()

        if not url:
            messagebox.showerror("错误", "请输入网页地址或选择文件")
            return
        if not name:
            messagebox.showerror("错误", "请输入应用名称")
            return

        # 生成临时的PyWebview脚本（增强交互性）
        temp_script = f"""
import webview
import os

def main():
    url = "{url}"
    if os.path.exists(url):
        url = f"file:///{os.path.abspath(url)}"
    window = webview.create_window("{name}", 
        url=url, 
        width={width}, 
        height={height}
    )
    if "{icon}" != "":
        window.icon = "{icon}"
    
    @window.expose  # 关键修改
    def save_file():
        return webview.create_file_dialog(webview.SAVE_DIALOG)[0]
    
    webview.start()

if __name__ == "__main__":
    main()
        """.strip()

        with open("temp_app.py", "w") as f:
            f.write(temp_script)

        try:
            # 优化PyInstaller参数（参考[6][9]）
            args = [
                "pyinstaller",
                "--onefile",
                "--noconfirm",
                "--clean",
                "--windowed",
                "--name", name,
                "temp_app.py"
            ]
            if icon:
                args.extend(["--icon", icon])

            # 执行打包命令
            subprocess.run(args, check=True)
            messagebox.showinfo("成功", f"应用已打包至 dist/{name}")
        except subprocess.CalledProcessError as e:
            messagebox.showerror("错误", f"打包失败: {str(e)}")
        finally:
            # 清理临时文件
            os.remove("temp_app.py")


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()